package com.hwadee.springboot.controller.ExamController;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hwadee.springboot.entity.Exam;
import com.hwadee.springboot.entity.ExamRequest;
import com.hwadee.springboot.entity.Question;
import com.hwadee.springboot.entity.R;
import com.hwadee.springboot.service.ExamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/examApi/exams")
public class ExamController {

    @Autowired
    private ExamService examService;

    @PostMapping
    public R createExam(@RequestBody Exam exam) {
        boolean saved = examService.save(exam);
        if (saved) {
            return R.ok("考试创建成功", exam);
        } else {
            return R.error(500, "考试创建失败");
        }
    }

    @PostMapping("/publish")
    public R<String> publishExam(@RequestBody ExamRequest request) {
        try {
            Exam exam = new Exam();
            exam.setName(request.getName());
            exam.setStartTime(request.getStartTime());
            exam.setEndTime(request.getEndTime());
            exam.setDescription(request.getDescription());

            // 将题目列表转换为 JSON 字符串并存储到 questions 字段
            ObjectMapper objectMapper = new ObjectMapper();
            String questionsJson = objectMapper.writeValueAsString(request.getQuestions());
            exam.setQuestions(questionsJson);

            Boolean result = examService.publishExam(exam);
            if (!result) {
                return R.error(500, "考试发布失败");
            }
            return R.ok("考试发布成功");
        } catch (Exception e) {
            return R.error(500, "发布考试失败: " + e.getMessage());
        }
    }

    @GetMapping("/available")
    public R<?> getAvailableExams(@RequestParam Long studentId) {
        try {
            List<Exam> availableExams = examService.getAvailableExams(studentId);
            return R.ok().data(availableExams);
        } catch (Exception e) {
            return R.error(500, "获取考试列表失败: " + e.getMessage());
        }
    }

    @GetMapping
    public R getAllExams() {
        List<Exam> exams = examService.list();
        return R.ok("查询成功", exams);
    }



    @GetMapping("/{id}/questions")
    public R<List<Question>> getExamQuestions(@PathVariable Integer id) {
        try {
            List<Question> questions = examService.listQuestionsByExamId(id);
            return R.ok(questions);
        } catch (Exception e) {
            return R.error(500, "获取考试题目失败");
        }
    }
}